import Vue from 'vue'
import VueRouter from 'vue-router'
import Index from "../views/Index";
import Login from "../views/Login"

Vue.use(VueRouter)

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
    return originalPush.call(this, location).catch(err => err)
}

const routes = [
    {
        path: '/',
        redirect: '/login',
    },
    {
        path: '/login',
        component: Login,
        name: 'login'
    },
    {
        meta: {
            requireAuth: true //如果来该页面 需要验证（是否登录）
        },
        path: '/index',
        name: '图书首页',
        component: Index,
        children: [
            {
                meta: {
                    requireAuth: true //如果来该页面 需要验证（是否登录）
                },
                path: '/home',
                name: '服务中心',
                component: () => import('../components/Home')
            },
            {
                meta: {
                    requireAuth: true //如果来该页面 需要验证（是否登录）
                },
                path: '/showAll',
                name: '图书中心',
                component: () => import('../components/ShowAll')
            },
            {
                meta: {
                    requireAuth: true
                },
                path: '/myBorrow',
                name: '我的借阅',
                component: () => import('../components/MyBorrow')
            }
        ]
    },
    {
        meta:{
            requireAuth: true
        },
        path: '/index',
        name: '用户管理',
        component: Index,
        children: [
            {
                meta: {
                    requireAuth: true //如果来该页面 需要验证（是否登录）
                },
                path: '/allUsers',
                name: '用户中心',
                component: () => import('../views/admin/AllUsers')
            }
        ]
    },
]

const router = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL, routes
})

export default router

//添加全局路由拦截
router.beforeEach((to, from, next) => {
    if (to.meta.requireAuth) {
        //如果去的页面需要认证 那么就开始认证是否登录成功
        if (sessionStorage.getItem("token") == 'true') {
            next(); //放行
        } else {
            //否则下一步也放行 但放行到登录页面
            next({
                path: '/login'
            })
        }
    } else { //如果不需要授权 比如直接去登录页面
        if (sessionStorage.getItem("token") == 'true' && to.path != '/login') {
            next('/index')
        } else {
            next()
        }
    }
})

